<%@page import="snake.Player.Direction"%>
<%@page import="utils.LoggedUser"%>
<%@page import="snake.GamePackage" %>
<%@page import="java.util.List" %>
<%@page import="snake.Player" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@include file="/jsp/header.jsp" %>
    
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<script type="text/javascript">
<%
	LoggedUser loggedUser = (LoggedUser) session.getAttribute("LoggedUser");
	int userId = loggedUser.getId();
	Direction direction = Direction.EAST;
	int gameId = -1;
	
	List<GamePackage> gamePackage = (List<GamePackage>)request.getServletContext().getAttribute("startedGames");
	
	if(request.getSession().getAttribute("gameId")!=null)
	{
		gameId = (Integer)request.getSession().getAttribute("gameId");
		
		for(Player p : gamePackage.get(gameId).getPlayersList())
		{
			if(p.getId() == userId)
			{
				direction = p.getDirection();
			}
		}
	}
	
%>
$(document).ready(function() {	
	
	var ip = location.host;
	var waiting=3;
var gameId = "<%=gameId%>";
var direction  = "<%=direction%>";
var userId = "<%=userId%>";
var mess = "";
var websocket;

if("WebSocket" in window)
{
	websocket = new WebSocket("ws://"+ip+"/snake/testCont");
	mess = gameId + ":"+direction+":"+userId;
	
  	websocket.onopen = function()
  	{
       websocket.send(mess);
    };  
    
    window.onbeforeunload = function() 
    {
        websocket.onclose = function () {}; // disable onclose handler first
        websocket.close();
    };

	
	websocket.onmessage = function processMessage(message)
	{
		var jsonData = JSON.parse(message.data);
		
		if(jsonData !== 'undefined' && jsonData!="" && jsonData!=null)
		{			
			if(jsonData.gameStatus=="WAITING")
				{
					$("#messageDiv").text("Starting :"+waiting);
					waiting--;
					
				}
			if(jsonData.gameStatus=="PLAYING")
				{
					$("#messageDiv").text("PLAYING");
				}
			
				 var canvas = document.getElementById("myCanvas");
			 	 var ctx = canvas.getContext("2d");
			     var userId = [];
			     
			     for(var i=0; i<jsonData.playersList.length; i++)
			     {
			      userId[i] = jsonData.playersList[i].id;
			     }
			     
			     function draw(x,y,width,height,color)
			     {
			      ctx.fillStyle = color;
			      ctx.fillRect(x,y,width,height);
			     }
			     
			     for(var i = 0; i < jsonData.matrix.length; i++)
			     {
			      for(var j=0; j < jsonData.matrix[i].length; j++)
			       {
			        if(jsonData.matrix[j][i]==userId[0])
			        {
			         draw(i*10,j*10,10,10,"#FF0000");
			        }
			        else if(jsonData.matrix[j][i]==userId[1])
			        {
			         draw(i*10,j*10,10,10,"#00FF66");
			        }
			        else if(jsonData.matrix[j][i]==userId[2])
			        {
			         draw(i*10,j*10,10,10,"#9900CC");
			        }
			        else if(jsonData.matrix[j][i]==userId[3])
			        {
			         draw(i*10,j*10,10,10,"#0033FF");
			        }
			        if(jsonData.matrix[j][i]==0)
		        	{
		        		draw(i*10,j*10,10,10,"#FFFFFF");
		        	}
			        if(jsonData.matrix[j][i]==-1)
		        	{
		        		draw(i*10,j*10,10,10,"#000000");
		        	}
			       
			       }
			     }
			     $("#pointsDiv").empty();
			     var score="";
			     for(var k=0;k<jsonData.playersList.length;k++)
			    	 {
			    	 	score+=jsonData.playersList[k].username+" : "+jsonData.playersList[k].score+"<br>";			    		 
			    	 }
			     $("#pointsDiv").html(score);
			    
			

					if(jsonData.gameStatus=="FINISHED")
						{
							$("#leaveButton").css("visibility","visible");
							
							$.post( "gameOver", {},function()
									{
										
									});
							websocket.close();
							alert("GAME OVER!");
						}
					
					//console.log(jsonData);
				
				}
				else
					{					
						$("#leaveButton").css("visibility","visible");
						
						
						$.post( "gameOver", { },function()
								{
									
								});
						
						websocket.close();
						alert("GAME OVER!");
						
					}
		
	
}
	$(window).keydown(function(e){
		if(e.which==37)//west
		{
			direction = "WEST";
			mess = gameId + ":"+direction+":"+userId;
			websocket.send(mess);
		}
		else if(e.which==38)//north
		{
			direction = "NORTH";
			mess = gameId + ":"+direction+":"+userId;
			websocket.send(mess);
		}
		else if(e.which==39)//east
		{
			direction = "EAST";
			mess = gameId + ":"+direction+":"+userId;
			websocket.send(mess);
		}
		else if(e.which==40)//south
		{
			direction = "SOUTH";
			mess = gameId + ":"+direction+":"+userId;
			websocket.send(mess);
		}
	});
}
else
	{
	    // the browser doesn't support WebSockets
	    alert("WebSockets NOT supported here!\r\n\r\nBrowser: " + navigator.userAgent + "\r\n\r\ntest by jimbergman.net (based on Google sample code)");
	}

});
</script>
</head>
<body>


<div id="matrix" style="width: 400px;"></div>
<br><br>
<H2 id="messageDiv"></H2>

<div id="pointsDiv">puncte multe</div>

<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;"></canvas>
<input id="leaveButton" type="button" value="Leave Game" style="visibility: hidden; " onclick="window.location.href='leaveGame'">

</body>
</html>